// src/utils/websocket.js
class WebSocketService {
  constructor(url) {
    this.url = url;
    this.ws = null;
    this.reconnectInterval = 5000; // 重连间隔时间(毫秒)
    this.heartbeatInterval = 30000; // 心跳间隔时间(毫秒)
    this.reconnectTimeout = null;
    this.heartbeatTimeout = null;
    this.isManualClose = false; // 是否手动关闭连接
    this.callbacks = {
      onOpen: null,
      onMessage: null,
      onClose: null,
      onError: null
    };
  }

  // 连接WebSocket
  connect() {
    try {
      this.ws = new WebSocket(this.url);
      this.setupEventHandlers();
    } catch (error) {
      console.error('WebSocket连接失败:', error);
      this.handleReconnect();
    }
  }

  // 设置事件处理器
  setupEventHandlers() {
    this.ws.onopen = (event) => {
      console.log('WebSocket连接已建立');
      if (this.callbacks.onOpen) {
        this.callbacks.onOpen(event);
      }
      this.startHeartbeat();
    };

    this.ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      // 处理心跳响应
      if (data.type === 'heartbeat' && data.message === 'pong') {
        console.log('收到心跳响应');
        return;
      }
      
      if (this.callbacks.onMessage) {
        this.callbacks.onMessage(data, event);
      }
    };

    this.ws.onclose = (event) => {
      console.log('WebSocket连接已关闭', event);
      this.clearTimers();
      
      if (this.callbacks.onClose) {
        this.callbacks.onClose(event);
      }
      
      // 如果不是手动关闭，则尝试重连
      if (!this.isManualClose) {
        this.handleReconnect();
      }
    };

    this.ws.onerror = (event) => {
      console.error('WebSocket发生错误', event);
      if (this.callbacks.onError) {
        this.callbacks.onError(event);
      }
    };
  }

  // 开始心跳检测
  startHeartbeat() {
    this.clearHeartbeat();
    
    this.heartbeatTimeout = setInterval(() => {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.send({
          type: 'heartbeat',
          message: 'ping'
        });
      }
    }, this.heartbeatInterval);
  }

  // 清除心跳定时器
  clearHeartbeat() {
    if (this.heartbeatTimeout) {
      clearInterval(this.heartbeatTimeout);
      this.heartbeatTimeout = null;
    }
  }

  // 处理重连
  handleReconnect() {
    if (this.isManualClose) return;
    
    console.log(`将在 ${this.reconnectInterval / 1000} 秒后尝试重连...`);
    this.clearReconnect();
    
    this.reconnectTimeout = setTimeout(() => {
      console.log('尝试重新连接...');
      this.connect();
    }, this.reconnectInterval);
  }

  // 清除重连定时器
  clearReconnect() {
    if (this.reconnectTimeout) {
      clearTimeout(this.reconnectTimeout);
      this.reconnectTimeout = null;
    }
  }

  // 清除所有定时器
  clearTimers() {
    this.clearHeartbeat();
    this.clearReconnect();
  }

  // 发送消息
  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data));
      return true;
    }
    console.warn('WebSocket未连接，无法发送消息');
    return false;
  }

  // 关闭连接
  close() {
    this.isManualClose = true;
    this.clearTimers();
    
    if (this.ws) {
      this.ws.close();
    }
  }

  // 设置回调函数
  setOnOpen(callback) {
    this.callbacks.onOpen = callback;
  }

  setOnMessage(callback) {
    this.callbacks.onMessage = callback;
  }

  setOnClose(callback) {
    this.callbacks.onClose = callback;
  }

  setOnError(callback) {
    this.callbacks.onError = callback;
  }
}

export default WebSocketService;